/**
 * 2017年12月20日
 */
package com.cmwa.scbp.sys.msg.filter;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import com.cmwa.scbp.sys.msg.filter.entity.MsgFilterConfigVo;
import com.cmwa.scbp.sys.msg.filter.service.MsgFilterConfigService;
import com.cmwa.scbp.utils.spring.SpringContextUtil;

/**
 * @author ex-zuotc
 * 2017年12月20日
 */
@Component("msgFilterChainFactory")
public class MsgFilterChainFactory {
	
	@Resource
	private MsgFilterConfigService msgFilterConfigService;
    
    public MsgFilterChain createFilterChain(String msgCode) throws ClassNotFoundException {
    	MsgFilterChainImpl filterChain = null;
    	
    	List<MsgFilterConfigVo> configVos = msgFilterConfigService.queryFilterConfigs(msgCode);
    	if (CollectionUtils.isNotEmpty(configVos)) {
    		List<MsgFilterConfig> msgFilters = new ArrayList<MsgFilterConfig>();
    		
    		for (MsgFilterConfigVo configVo : configVos) {
    			MsgFilter filter = getFilterImplByType(configVo.getFilterType());
    			if (filter == null) {
    				continue;
    			}
    			
    			msgFilters.add(new MsgFilterConfig(configVo.getFilterParam(), filter));
    		}
    		
    		filterChain = new MsgFilterChainImpl(msgFilters);
    	}
    	return filterChain;
    }
    
    private MsgFilter getFilterImplByType(String filterType) throws ClassNotFoundException {
    	Class<?> clazz = Class.forName(filterType);
    	
    	Object filter = SpringContextUtil.getBean(clazz);
    	if (filter instanceof MsgFilter) {
    		return (MsgFilter) filter;
    	}
    	return null;
    }
}
